# -*-coding:utf-8-*-
import json
import os
import re
import shutil
import time
from time import sleep
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from retrying import retry
from Logs.log import log1
from csv_format.utils import wait_time
from PIL import ImageGrab
from utils import files_csv_list, pro_files, zipDir, update_po


class logitech:
    def __init__(self):
        self.url = "https://external-qa.logitech.com"
        self.driver = webdriver.Chrome()
        self.master_name = ""
        self.txn_name = ""
        self.pro_file = pro_files
        self.png_path = ""

    def parse_url(self):  # 发送请求
        self.driver.maximize_window()
        self.driver.get(self.url)

    def login(self):  # 登录
        user_name = WebDriverWait(self.driver, wait_time).until(
            lambda driver: self.driver.find_element_by_id("unamebean"))
        password = WebDriverWait(self.driver, wait_time).until(lambda driver: self.driver.find_element_by_id("pwdbean"))
        user_name.send_keys('ISPSHE')
        password.send_keys('ISPSHE')
        WebDriverWait(self.driver, wait_time).until(EC.element_to_be_clickable((By.ID, "SubmitButton"))).click()

    def get_files(self, file_dir):
        # 读取files_address的[master,txn].csv路径
        # file_dir = os.path.dirname(os.path.abspath(__file__)) + "\\files_address\\455290925_1"
        # print(file_dir)
        files = os.listdir(file_dir)
        master_file = ""
        txn_file = ""
        for file in files:
            if file.split(".")[-1] == "csv" and re.search(r"MASTER", file):
                master_file = os.path.join(file_dir, file)
                self.master_name = file.split(".")[0]
                # print(master_file)
                # master_files.append(master_file)
            elif file.split(".")[-1] == "csv" and re.search(r"TXN", file):
                txn_file = os.path.join(file_dir, file)
                self.txn_name = file.split(".")[0]
                # print(txn_file)
                # txn_files.append(txn_file)
        # if not (master_file and txn_file):
        #     print("无符合格式的文件")
        #     log1.info("无符合格式的文件")
        return master_file, txn_file

    def enter_upload(self):
        # 点击LOGI LSTAR Supplier User文件夹
        li = WebDriverWait(self.driver, wait_time).until(
            EC.element_to_be_clickable((By.XPATH, "//li[@id='51495:60005:-1:0']/a")))
        li.click()
        # 点击Master Upload
        WebDriverWait(li, wait_time).until(
            EC.element_to_be_clickable((By.XPATH, "//li[@id='LOGI_LSTAR_Supplier_UserTransactionsSerials']/a"))).click()

    def upload_master_file(self, region):  # 上传文件
        # sleep(5)
        # 输入region代码,点击查询
        input = WebDriverWait(self.driver, wait_time).until(
            lambda driver: self.driver.find_element_by_xpath("//span[@id='Region__xc_0']/input[@id='Region']"))
        input.send_keys(region)
        # WebDriverWait(self.driver, wait_time).until(
        #     lambda driver: self.driver.find_element_by_xpath("//span[@id='Region__xc_0']/a")).click()
        # MASTER页面点击upload
        WebDriverWait(self.driver, wait_time).until(
            EC.element_to_be_clickable((By.XPATH, "//table[@id='PageBtnbarRN']//button[@id='Uploadmaster']"))).click()
        # sleep(180),获取Batch id
        sleep(60)
        # str = "Your file has been uploaded for processing. And request with 185325059 has been submitted for further processing.Batch id is 566819 Please query batch id below for status..."
        try:
            conf = WebDriverWait(self.driver, wait_time).until(
                lambda driver: self.driver.find_element_by_xpath(
                    "//table[@id='FwkErrorBeanId']//div[@class='x47']")).text
            Batch_id = re.search(r"Batch id is (\d+)", conf).group(1)
            print(Batch_id)
        except:
        # 刷新页面
            self.driver.refresh()
            sleep(60)
            conf = WebDriverWait(self.driver, wait_time).until(
                lambda driver: self.driver.find_element_by_xpath(
                    "//table[@id='FwkErrorBeanId']//div[@class='x47']")).text
            Batch_id = re.search(r"Batch id is (\d+)", conf).group(1)
        # 输入Batch id点击search
        WebDriverWait(self.driver, wait_time).until(
            lambda driver: self.driver.find_element_by_xpath(
                "//span[@id='BatchID__xc_0']/input[@id='BatchID']")).send_keys(Batch_id)

    def upload_txn_file(self, region):  # 上传文件
        # 输入region代码,点击查询
        input = WebDriverWait(self.driver, wait_time).until(
            lambda driver: self.driver.find_element_by_xpath("//span[@id='Region__xc_0']/input[@id='Region']"))
        input.send_keys(region)
        # WebDriverWait(self.driver, wait_time).until(
        #     lambda driver: self.driver.find_element_by_xpath("//span[@id='Region__xc_0']/a")).click()
        # TXN页面点击upload
        WebDriverWait(self.driver, wait_time).until(
            EC.element_to_be_clickable((By.XPATH, "//table[@id='PageUploadbarRN']//button[@id='UploadSupp']"))).click()
        # sleep(180),获取Batch id
        sleep(60)
        # 刷新页面
        # self.driver.refresh()
        # sleep(60)
        # str = "Your file has been uploaded for processing. And request with 185325059 has been submitted for further processing.Batch id is 566819 Please query batch id below for status..."
        try:
            conf = WebDriverWait(self.driver, wait_time).until(
                lambda driver: self.driver.find_element_by_xpath("//table[@id='FwkErrorBeanId']//div[@class='x47']")).text
            Batch_id = re.search(r"Batch id is (\d+)", conf).group(1)
            print(Batch_id)
        except:
            # 刷新页面
            self.driver.refresh()
            sleep(60)
            conf = WebDriverWait(self.driver, wait_time).until(
                lambda driver: self.driver.find_element_by_xpath(
                    "//table[@id='FwkErrorBeanId']//div[@class='x47']")).text
            Batch_id = re.search(r"Batch id is (\d+)", conf).group(1)
        # 输入Batch id
        WebDriverWait(self.driver, wait_time).until(
            lambda driver: self.driver.find_element_by_xpath(
                "//span[@id='BatchID__xc_0']/input[@id='BatchID']")).send_keys(Batch_id)

    def error_report(self, num=0):
        for i in range(3):
            # 点击search
            WebDriverWait(self.driver, wait_time).until(
                EC.element_to_be_clickable((By.XPATH, "//table[@id='SearchRN']//button[@id='Search']"))).click()
            master_dict = {}
            table = WebDriverWait(self.driver, wait_time).until(
                lambda driver: self.driver.find_element_by_xpath("//table[@id='region1']"))
            ErrorRecords = WebDriverWait(table, wait_time).until(
                lambda driver: table.find_element_by_xpath("//span[@title='Error Records:']")).text
            master_dict["ErrorRecords"] = ErrorRecords
            # if int(ErrorRecords)>0:
            # 提取TotalSuccessRecords, Total Records in file及表格内容
            # 上传成功数量 / Total Success Records:
            TotalSuccessRecords = WebDriverWait(table, wait_time).until(
                lambda driver: table.find_element_by_xpath("//span[@title='/ Total Success Records:']")).text
            master_dict["TotalSuccessRecords"] = TotalSuccessRecords
            # 上传记录数量 / Total Records in file :
            if num == 0:
                TotalRecords = WebDriverWait(table, wait_time).until(
                    lambda driver: table.find_element_by_xpath("//span[@title='/ Total Records in file:']")).text
            else:
                TotalRecords = WebDriverWait(table, wait_time).until(
                    lambda driver: table.find_element_by_xpath("//span[@title='/ Total Records in file :']")).text
            master_dict["TotalRecords"] = TotalRecords
            # 表格内容ErrorCode,MasterFileName,SerialNumber,ErrorDescription,ErrorStatus
            data_list = self.table_data(num)
            if data_list:
                self.save_error_png(num)
                master_dict["table_data"] = data_list
                return master_dict
            else:
                sleep(60)
        # 点击3次search仍无数据,截屏保存
        self.save_error_png(num)

    def table_data(self, num):
        table = WebDriverWait(self.driver, wait_time).until(
            lambda driver: self.driver.find_element_by_class_name("x1p"))
        trs = WebDriverWait(table, wait_time).until(
            lambda driver: table.find_elements_by_xpath("./tbody/tr"))
        data_list = []
        # 标题
        tr1 = trs[0]
        titles = WebDriverWait(tr1, wait_time).until(
            lambda driver: tr1.find_elements_by_xpath("./th/span"))
        # ErrorCode = WebDriverWait(table, wait_time).until(
        #     lambda driver: table.find_element_by_id("sortableHeader1")).text.replace(" ","")
        # MasterFileName = WebDriverWait(table, wait_time).until(
        #     lambda driver: table.find_element_by_id("sortableHeader5")).text.replace(" ","")
        # SerialNumber = WebDriverWait(table, wait_time).until(
        #     lambda driver: table.find_element_by_id("sortableHeader4")).text.replace(" ","")
        # ErrorDescription = WebDriverWait(table, wait_time).until(
        #     lambda driver: table.find_element_by_id("sortableHeader2")).text.replace(" ","")
        # ErrorStatus = WebDriverWait(table, wait_time).until(
        #     lambda driver: table.find_element_by_id("sortableHeader3")).text.replace(" ","")
        # 内容
        for tr in trs[1:]:
            data_dict = {}
            try:
                vals = WebDriverWait(tr, wait_time).until(
                    lambda driver: tr.find_elements_by_xpath("./td/span"))
            except:
                return data_list
            if not vals[-1].text:
                return data_list
            # if vals[-1].text != "S":
            #     self.save_error_png(num)
            for i in range(len(titles)):
                data_dict[titles[i].text.replace(" ", "")] = vals[i].text
            data_list.append(data_dict)
        # print(data_list)
        return data_list

    def save_error_png(self, num):
        bbox = (0, 104, 1920, 1080)
        im = ImageGrab.grab(bbox)
        # 参数 保存截图文件的路径
        if num == 0:
            im.save('{}/{}.png'.format(self.png_path, self.master_name))
        else:
            im.save('{}/{}.png'.format(self.png_path, self.txn_name))

    def save_master(self, dict):
        js = json.dumps(dict, indent=4, separators=(',', ':'), ensure_ascii=False)
        with open("csv_format/json_save/{}.json".format(self.master_name), "w+") as f:
            f.write(js)

    def save_txn(self, dict):
        js = json.dumps(dict, indent=4, separators=(',', ':'), ensure_ascii=False)
        with open("csv_format/json_save/{}.json".format(self.txn_name), "w+") as f:
            f.write(js)

    def run(self):  # 主逻辑
        hour = time.strftime("%Y%m%d%H")
        # 新建保存图片目录
        # save_address = "csv_format/error_png"
        # self.png_path = os.path.join(save_address, hour)
        curr_path = os.path.abspath(os.path.dirname(__file__))
        save_address = os.path.join(curr_path, "error_png")
        self.png_path = os.path.join(save_address, hour)
        try:
            os.makedirs(self.png_path)
        except:
            print("{}已存在".format(self.png_path))
            log1.error("{}已存在".format(self.png_path))
        try:
            self.parse_url()
            self.login()
        except:
            self.driver.refresh()
            sleep(3)
            self.login()
        # 点击进入上传文件页面
        self.enter_upload()
        # 读取master和txn文件
        files = files_csv_list()
        if not files:
            print("files_address目录中无上传文件")
            log1.error("files_address目录中无上传文件")
            return
        for file_dir in files:
            po = re.search(r"(.*)\\(.*)", file_dir).group(2)
            master_files, txn_files = self.get_files(file_dir)
            if (not master_files) or (not txn_files):
                print("无符合格式的文件")
                # log1.info("无符合格式的文件")
                # 将文件目录移到已上传的目录(process_files)
                try:
                    shutil.move(file_dir, self.pro_file)
                except:
                    old_file = os.path.join(self.pro_file, po)
                    shutil.rmtree(old_file)
                    shutil.move(file_dir, self.pro_file)
                continue
            try:
                # 点击Master File Upload
                WebDriverWait(self.driver, wait_time).until(
                    EC.element_to_be_clickable((By.ID, "LSTAR_UPLOADS_FILE"))).click()
                # 点击选择文件
                upload = WebDriverWait(self.driver, wait_time).until(
                    lambda driver: self.driver.find_element_by_id("LSTARfileUpload_oafileUpload"))
                # 选择本地文件
                upload.send_keys(master_files)
                # 提取master_file中region的代码
                region = re.search(r"_MASTER_(.*).csv", master_files).group(1)
                # 上传master文件
                self.upload_master_file(region)
                # 提取errorReport
                master_dict = self.error_report()
                if not master_dict:
                    print("无master报告数据或提取失败")
                    continue
                self.save_master(master_dict)
                # sleep(30*60)
                # 上传txn文件
                # 点击FG Supplier Transaction Upload
                WebDriverWait(self.driver, wait_time).until(
                    EC.element_to_be_clickable((By.ID, "LSTAR_UPLOADS_FROMSUPPLR_FILE"))).click()
                # 点击选择文件
                upload = WebDriverWait(self.driver, wait_time).until(
                    lambda driver: self.driver.find_element_by_id("TrnSupplFileupload_oafileUpload"))
                # 选择本地文件
                upload.send_keys(txn_files)
                # 提取master_file中region的代码
                region = re.search(r"_TXN_(.*).csv", txn_files).group(1)
                self.upload_txn_file(region)
                # sleep(60)
                # 提取errorReport
                txn_dict = self.error_report(1)
                if not txn_dict:
                    print("无txn报告数据或提取失败")
                    continue
                # 保存errorReport
                self.save_txn(txn_dict)
                sleep(10)
                print("{}MASTER,TXN上传成功".format(po))
                log1.info("{}MASTER,TXN上传成功".format(po))
                update_po("1", po)
            except:
                print("{}MASTER,TXN上传失败".format(po))
                log1.info("{}MASTER,TXN上传失败".format(po))
                # 修改数据表状态
                update_po("2", po)
            # 将文件目录移到已上传的目录(process_files)
            try:
                shutil.move(file_dir, self.pro_file)
            except:
                old_file = os.path.join(self.pro_file, po)
                shutil.rmtree(old_file)
                # self.pro_file = "C:\\Users\\hhh\\Desktop\\Demo\\logitech\\process_files\\already_exist"
                shutil.move(file_dir, self.pro_file)
        self.driver.close()
        # 压缩图片文件夹
        zip_png_path = save_address + "\\{}.zip".format(hour)
        # print(zip_png_path)
        zipDir(self.png_path, zip_png_path)
        return zip_png_path


def run():
    lg = logitech()
    zip_png_path = lg.run()
    return zip_png_path


if __name__ == '__main__':
    run()